<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\Response;
use app\common\model\Transfer as TransferModel;
use think\exception\ValidateException;

class Transfer extends Base
{
    public function index(): Response
    {
        $result['account'] = [
            [
                'title' => get_pay_way('currency'),
                'type' => 'currency',
                'balance' => $this->user->assets->currency
            ],
            [
                'title' => get_pay_way('green'),
                'type' => 'green',
                'balance' => $this->user->assets->green
            ]
        ];
        $result['factor'] = [
            'transfer_open' => $this->system['transfer_open'],
            'transfer_cross_line' => $this->system['transfer_cross_line'],
            'transfer_lower_open' => $this->system['transfer_lower_open'],
            'transfer_min' => $this->system['transfer_min'],
            'transfer_bs' => $this->system['transfer_bs'],
            'transfer_cost' => $this->system['transfer_cost'],
            'transfer_msg' => handleRichText($this->system['transfer_msg'])
        ];

        return Result::success('success', $result);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Transfer');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(TransferModel::add($param, $this->user, $this->system));
    }

    public function record(): Response
    {
        $list = TransferModel::getPageList(['uid|take_uid' => $this->user->id],
            'id,account,uid,take_uid,amount,cost,real_amount,create_time,note',
            $this->getPage(), $this->getLimit(), false, ['take', 'user']);
        foreach ($list['data'] as &$item) {
            if ($item->uid == $this->user->id) {
                $item->trStatus = '转出';
                $item->trUser = $item->take->code . '-' . $item->take->nickname;
            } else {
                $item->trStatus = '转入';
                $item->trUser = $item->user->code . '-' . $item->user->nickname;
            }
            unset($item->user, $item->take);
        }

        return Result::fastReturn($list);
    }
}